package com.kzd.gtboon.main.home

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.palette.graphics.Palette
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ColorUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.kzd.gtboon.R
import com.kzd.gtboon.callback.AnimationOnScrollListener
import com.kzd.gtboon.custom.setTransitionStatusE
import com.kzd.gtboon.databinding.IncludeAppRefreshBinding
import com.kzd.gtboon.entity.GameBanner
import com.kzd.gtboon.jetpack.vm.HomeViewModel
import com.kzd.gtboon.main.*
import com.kzd.gtboon.main.game.adapter.Game4Adapter
import com.kzd.gtboon.main.home.adapter.HOME_FEATURED_TYPE_100
import com.kzd.gtboon.main.home.adapter.HomeFeaturedAdapter
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewBindingFragment
import com.module.lemlin.owner.ownerViewModel
import com.youth.banner.Banner
import com.youth.banner.listener.OnPageChangeListener

class HomeFeaturedFragment : OwnerViewBindingFragment<IncludeAppRefreshBinding>(),
    AnimationOnScrollListener.OnAnimationScrollChangeListener {

    companion object {
        fun newInstance(): HomeFeaturedFragment {
            return HomeFeaturedFragment()
        }
    }

    private val mHomeFeaturedAdapter = HomeFeaturedAdapter()

    val mViewModel: HomeViewModel by lazy {
        ownerViewModel(requireParentFragment())
    }

    override val inflate: (LayoutInflater, ViewGroup?, Boolean) -> IncludeAppRefreshBinding
        get() = IncludeAppRefreshBinding::inflate

    override fun initView() {

        mViewBinding.rvAppRefreshBody.apply {
            layoutManager = LinearLayoutManager(context)
        }.apply {
            adapter = mHomeFeaturedAdapter
        }.addOnScrollListener(AnimationOnScrollListener().apply {
            setOnAnimationScrollListener(this@HomeFeaturedFragment)
        })

        mHomeFeaturedAdapter.setOnItemClickListener { _, _, position ->
            val itemData = mHomeFeaturedAdapter.getItem(position)
            if (!itemData.game_layout.isNullOrEmpty()) {
                mViewModel.homeDoings(itemData.game_layout)
            } else if (itemData.type == 3 || itemData.type == 4) {
                val index = when (itemData.type) {
                    3 -> 0
                    4 -> 2
                    else -> 0
                }
                toHomeTravelActivity(index)
            }
        }

        mHomeFeaturedAdapter.setOnItemHomeNav { _, nav ->
            if (nav.type == 1) {
                toHomeTravelActivity()
            } else if (nav.type == 2) {
                mViewModel.homeDoings("GMList")
            } else if (nav.type == 3) {
                toHomeCouponActivity()
            } else if (nav.type == 4) {
                toHomeServiceActivity()
            } else if (nav.type == 5) {
                toHomePresentActivity()
            }
        }

        mHomeFeaturedAdapter.setOnItemReserve { _, position, reserve ->
            val gid = reserve.id
                ?: return@setOnItemReserve
            val type = if (reserve.is_yuyue)
                "1" else "0"
            checkLogin {
                mViewModel.reserveChange(gid, type, position)
            }
        }

        mViewBinding.mSmartRefreshLayout.setOnRefreshListener {
            mViewModel.homeIndex()
        }
    }


    override fun initData() {
        mViewModel.homeIndex()
    }


    override fun initViewMode() {
        mViewModel.indexHomeLiveData.observe(viewLifecycleOwner, { response ->
            setTransitionStatusE(response,
                mHomeFeaturedAdapter,
                mViewBinding.mSmartRefreshLayout,
                (false))
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            data.find { it.type == HOME_FEATURED_TYPE_100 }?.apply {
                val list = getConversionList(GameBanner::class.java)
                if (list.isNullOrEmpty()) {
                    return@apply
                }
                mHomeFeaturedAdapter.setHeaderView(
                    createHeaderView(list)
                )
            }.let {
                data.remove(it)
            }
            mHomeFeaturedAdapter.setNewInstance(data)
            mHomeFeaturedAdapter.setFooterView(createFooterView())
        })

        mViewModel.reserveChangeLiveData.observe(viewLifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            val position = response.data?.position
                ?: return@observe
            val data = response.data?.data
                ?: return@observe
            mHomeFeaturedAdapter.setDataHomeType4(position, data)
        })

        mViewModel.homeDoingsLiveData.observe(viewLifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data
                ?: return@observe
            toHomeDoingsActivity(data.top.title, mViewModel.mGameLayout, data)
        })
    }

    override fun onResume() {
        super.onResume()
        mBanHomeHeaderBody?.start()
    }

    override fun onPause() {
        super.onPause()
        mBanHomeHeaderBody?.stop()
    }

    override fun onScrollChanged(dy: Int) {
        mViewModel.homeChangeBarStyle(dy)
    }

    @SuppressLint("InflateParams")
    private fun createFooterView(): View =
        layoutInflater.inflate(R.layout.view_home_footer, null)

    private var mBanHomeHeaderBody: Banner<GameBanner, *>? = null

    @SuppressLint("InflateParams")
    private fun createHeaderView(data: MutableList<GameBanner>): View =
        layoutInflater.inflate(R.layout.view_home_header, null).apply {
            val clHomeHeaderBg = findViewById<ConstraintLayout>(R.id.clHomeHeaderBg)
            mBanHomeHeaderBody = findViewById(R.id.bannerHomeHeaderBody)
            mBanHomeHeaderBody?.setOrientation(Banner.HORIZONTAL)
            mBanHomeHeaderBody?.setBannerGalleryEffect((15), (10))
            mBanHomeHeaderBody?.setUserInputEnabled(true)
            mBanHomeHeaderBody?.adapter = Game4Adapter(data).apply {
                setOnBannerListener { data, _ ->
                    if (data !is GameBanner)
                        return@setOnBannerListener
                    toGameDetailsActivity(data.gid)
                }
            }
            mBanHomeHeaderBody?.addOnPageChangeListener(object : OnPageChangeListener {
                override fun onPageScrolled(
                    position: Int, positionOffset: Float, positionOffsetPixels: Int,
                ) = Unit

                override fun onPageSelected(position: Int) {
                    data[position].image?.let { setHeaderPalette(clHomeHeaderBg, it) }
                }

                override fun onPageScrollStateChanged(state: Int) = Unit
            })
            data[0].image?.let { setHeaderPalette(clHomeHeaderBg, it) }
        }

    private fun setHeaderPalette(view: View, image: String) =
        Glide.with(requireContext()).asBitmap().load(image).into(object : CustomTarget<Bitmap>() {
            override fun onResourceReady(
                resource: Bitmap, transition: Transition<in Bitmap>?,
            ) {
                Palette.from(resource).generate {
                    val colorsArray = intArrayOf(
                        it?.vibrantSwatch?.rgb ?: 0, ColorUtils.getColor(R.color.white)
                    )
                    val drawable = GradientDrawable().apply {
                        orientation = GradientDrawable.Orientation.TOP_BOTTOM
                        colors = colorsArray
                    }
                    view.background = drawable
                }
            }

            override fun onLoadCleared(placeholder: Drawable?) = Unit
        })
}